<template>
	<view class="detail-container">
		<!-- 订单头部 -->
		<view class="order-header">
			<view class="order-number-section">
				<view class="order-number">
					<text class="order-number-label">订单号</text>
					<text class="order-number-value">{{ orderDetail.order_no }}</text>
					<text class="copy-btn" @click="copyOrderNumber">复制</text>
				</view>
			</view>
<!--			<view class="customer-service" @click="contactService">-->
<!--				<image src="/static/icon/kefu2.png" class="service-icon" mode="aspectFit"></image>-->
<!--				<text class="service-text">客服</text>-->
<!--			</view>-->
		</view>

		<!-- 订单详情卡片 -->
		<view class="detail-cards">

			<!-- 收货地址 -->
			<view v-if="orderDetail.order_delivery === 'express' && orderDetail.address_detail" class="detail-card">
				<view class="detail-row">
					<text class="detail-label">收货人</text>
					<text class="detail-value">{{ orderDetail.address_nickname }}</text>
				</view>
				<view class="detail-row">
					<text class="detail-label">联系电话</text>
					<text class="detail-value">{{ orderDetail.address_phone }}</text>
				</view>
				<view class="detail-row">
					<text class="detail-label">收货地址</text>
					<text class="detail-value address-value">{{ orderDetail.address_detail }}</text>
				</view>
			</view>
      <view class="detail-card">
        <!-- 订单信息 -->
        <view class="order-product" v-for="item in orderDetail.orderItems">
          <image :src="item.product_cover" class="product-image" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-title">{{ item.product_name }}</text>
            <text class="product-desc">{{ getOrderDesc(item.sku_spec) }}</text>
            <text class="product-desc">x{{ item.count }}</text>
          </view>
          <view class="product-price">
            <text class="price-symbol">¥</text>
            <text class="price-value">{{ item.price || '0.00' }}</text>
          </view>
        </view>
      </view>
			<!-- 订单状态和价格 -->
			<view class="detail-card">
				<view class="detail-row">
					<text class="detail-label">订单状态</text>
					<view class="status-badge" :class="[getStatusClass(orderDetail.status)]">
						<text class="status-text">{{ getStatusText(orderDetail.status) }}</text>
					</view>
				</view>
				<view class="detail-row">
					<text class="detail-label">创建时间</text>
					<text class="detail-value">{{ formatTime(orderDetail.create_time) }}</text>
				</view>
				<view class="detail-row">
					<text class="detail-label">付款时间</text>
					<text class="detail-value">{{ formatTime(orderDetail.payment_time) || '--' }}</text>
				</view>
				<view class="detail-row price-row">
					<text class="detail-label">订单金额</text>
					<view class="price-section">
						<text class="price-symbol">¥</text>
						<text class="price-value">{{ orderDetail.amount || '0.00' }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 备注 -->
		<view class="remarks-section">
			<text class="remarks-title">备注</text>
			<view class="remarks-content">
				<text class="remarks-text">{{ orderDetail.remarks || '' }}</text>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="bottom-actions">
			<view v-if="orderDetail.status === 'pending_pricing'" class="action-buttons">
				<view class="action-btn secondary-btn" @click="contactPricing">
					<text class="action-text">联系定价</text>
				</view>
				<view class="action-btn reject-btn" @click="cancelOrder">
					<text class="action-text">取消订单</text>
				</view>
			</view>
			<view v-else-if="orderDetail.status === 'pending'" class="action-buttons">
				<view class="action-btn reject-btn" @click="cancelOrder">
					<text class="action-text">取消订单</text>
				</view>
				<view class="action-btn pay-btn" @click="payOrder">
					<text class="action-text">支付</text>
				</view>
			</view>
			<view v-else-if="orderDetail.status === 'paid'" class="action-buttons">
				<view class="action-btn secondary-btn" @click="viewLogistics">
					<text class="action-text">查看物流</text>
				</view>
				<!-- <view class="action-btn primary-btn" @click="confirmReceipt">
					<text class="action-text">确认收货</text>
				</view> -->
			</view>
			<view v-else-if="orderDetail.status === 'shipped'" class="action-buttons">
				<view class="action-btn secondary-btn" @click="viewLogistics">
					<text class="action-text">查看物流</text>
				</view>
				<!-- <view class="action-btn primary-btn" @click="confirmReceipt">
					<text class="action-text">确认收货</text>
				</view> -->
			</view>
			<view v-else-if="orderDetail.status === 'pending_receipt'" class="action-buttons">
				<view class="action-btn secondary-btn" @click="viewLogistics">
					<text class="action-text">查看物流</text>
				</view>
				<view class="action-btn primary-btn" @click="confirmReceipt">
					<text class="action-text">确认收货</text>
				</view>
			</view>
			<view v-else-if="orderDetail.status === 'completed'" class="action-buttons">
				<view class="action-btn secondary-btn" @click="viewLogistics">
					<text class="action-text">查看物流</text>
				</view>
				<!-- <view class="action-btn primary-btn" @click="writeReview">
					<text class="action-text">评价</text>
				</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				orderId: null,
				orderDetail: {},
			}
		},
		methods: {
      // 获取订单描述
      getOrderDesc(sku_spec) {
        let _sku_spec = JSON.parse(sku_spec)
        let desc = ''
        if (_sku_spec) {
          for (let key in _sku_spec) {
            desc += `${_sku_spec[key]} `
          }
        }
        return desc
      },
			// 复制订单号
			copyOrderNumber() {
				uni.setClipboardData({
					data: this.orderDetail.order_no,
					success: () => {
						uni.showToast({
							title: '订单号已复制',
							icon: 'success'
						});
					}
				});
			},
			// 获取收货方式
			getDeliveryMethod() {
				const methodMap = {
					'express': '快递',
					'self_pickup': '自提',
					'no_delivery': '虚拟'
				};
				return methodMap[this.orderDetail.order_delivery] || '--';
			},

			// 格式化时间
			formatTime(timeStr) {
				if (!timeStr) return '';
				const date = new Date(timeStr);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			},

			// 联系客服
			contactService() {
				uni.showActionSheet({
					itemList: ['在线客服', '电话客服'],
					success: (res) => {
						if (res.tapIndex === 0) {
							// 跳转到在线客服页面
							uni.navigateTo({
								url: '/pages/service/chat'
							});
						} else if (res.tapIndex === 1) {
							// 拨打电话
							uni.makePhoneCall({
								phoneNumber: '400-123-4567'
							});
						}
					}
				});
			},

			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'pending_pricing': '待定价',
					'pending': '待支付',
					'paid': '已付款',
					'shipped': '已发货',
					'pending_receipt': '待收货',
					'completed': '已完成',
					'cancelled': '已取消',
					'refunding': '退款中',
					'refunded': '已退款'
				};
				return statusMap[status] || '未知状态';
			},

			// 获取状态样式类
			getStatusClass(status) {
				const classMap = {
					'pending_pricing': 'status-pending-pricing',
					'pending': 'status-pending',
					'paid': 'status-paid',
					'shipped': 'status-shipped',
					'pending_receipt': 'status-pending-receipt',
					'completed': 'status-completed',
					'cancelled': 'status-cancelled',
					'refunding': 'status-refunding',
					'refunded': 'status-refunded'
				};
				return classMap[status] || 'status-unknown';
			},

			// 联系定价
			contactPricing() {
				uni.showModal({
					title: '联系定价',
					content: '是否联系工坊进行定价？',
					success: (res) => {
						if (res.confirm) {
							// 解析订单参数获取工坊信息
							let storeId = this.orderDetail.store_id;
							let storeName = this.getStoreName();

							// 跳转到客服聊天页面
							uni.navigateTo({
								url: `/pages/service/chat?id=${storeId}&name=${storeName}&order_id=${this.orderId}`
							});
						}
					}
				});
			},

			// 取消订单
			cancelOrder() {
				uni.showModal({
					title: '取消订单',
					content: '确认取消该订单？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '取消中...'
							});

							// 调用取消订单接口
							const cancelData = {
								id: this.orderId,
								user_id: this.userInfo.id
							};

							this.$api.cancelOrder(cancelData).then(res => {
								uni.hideLoading();
								uni.showToast({
									title: '订单已取消',
									icon: 'success'
								});
								// 更新订单状态
								this.orderDetail.status = 'cancelled';
							}).catch(error => {
								uni.hideLoading();
								console.error('取消订单失败:', error);
								uni.showToast({
									title: '取消失败',
									icon: 'none'
								});
							});
						}
					}
				});
			},

			// 支付订单
			payOrder() {
				uni.showModal({
					title: '确认支付',
					content: `确认支付订单 ${this.orderDetail.order_no}？金额：¥${this.orderDetail.amount || '0.00'}`,
					success: (res) => {
						if (res.confirm) {
							this.getPay(this.orderId)
						}
					}
				});
			},
			getPay(order_id) {
				uni.showLoading({
					title: '微信支付请求'
				});
				const that = this
				this.$api.createPay({
					order_id
				}).then(payment => {
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: payment.timestamp,
						nonceStr: payment.nonce_str,
						package: payment.package,
						signType: payment.signType,
						paySign: payment.paySign,
						success: (result) => {
							uni.showToast({
								title: '支付成功'
							});

							// 刷新订单状态
							that.orderDetail.status = 'paid';
						},
						fail: (result) => {
							uni.showToast({
								icon: 'none',
								title: '支付失败',
							});
						},
						complete: () => {

						}
					});
				})
			},
			// 查看物流
			viewLogistics() {
				uni.navigateTo({
					url: `/pages/order/logistics?id=${this.orderId}`
				});
			},

			// 确认收货
			confirmReceipt() {
				uni.showModal({
					title: '确认收货',
					content: '确认已收到商品？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '确认中...'
							});

							// 调用确认收货接口
							const confirmData = {
								order_id: this.orderId,
								user_id: this.userInfo.id
							};

							this.$api.confirmReceipt(confirmData).then(res => {
								uni.hideLoading();
								uni.showToast({
									title: '确认收货成功',
									icon: 'success'
								});
								// 更新订单状态
								this.orderDetail.status = 'completed';
							})
						}
					}
				});
			},

			// 写评价
			writeReview() {
				uni.navigateTo({
					url: `/pages/order/comment?id=${this.orderId}`
				});
			},

			// 加载订单详情
			loadOrderDetail() {
				uni.showLoading({
					title: '加载中...'
				});

				// 调用获取订单详情接口
				this.$api.getOrderDetail(this.orderId).then(res => {
					uni.hideLoading();
					if (res) {
						this.orderDetail = res;
					}
				}).catch(error => {
					uni.hideLoading();
					console.error('获取订单详情失败:', error);
					uni.showToast({
						title: '获取订单详情失败',
						icon: 'none'
					});
				});
			}
		},
		onLoad(options) {
			this.orderId = options.id;
			this.loadOrderDetail();
		}
	}
</script>

<style lang="scss" scoped>
	.detail-container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
	}

	// 订单头部
	.order-header {
		background-color: #fff;
		padding: 32rpx;
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		border-bottom: 1rpx solid #f0f0f0;

		.order-number-section {
			flex: 1;

			.order-number {
				display: flex;
				align-items: center;
				gap: 16rpx;

				.order-number-label {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}

				.order-number-value {
					font-size: 28rpx;
					color: #333;
					font-weight: 600;
				}

				.copy-btn {
					font-size: 24rpx;
					color: #539DF3;
					padding: 4rpx 8rpx;
					border-radius: 4rpx;
					background-color: rgba(255, 107, 53, 0.1);

					&:active {
						background-color: rgba(255, 107, 53, 0.2);
					}
				}
			}
		}

		.customer-service {
			display: flex;
			align-items: center;
			gap: 8rpx;
			padding: 8rpx 16rpx;
			border-radius: 8rpx;
			background-color: #f5f5f5;

			.service-icon {
				width: 32rpx;
				height: 32rpx;
			}

			.service-text {
				font-size: 26rpx;
				color: #333;
			}

			&:active {
				background-color: #e8e8e8;
			}
		}
	}

	// 服务信息
	.service-info {
		background-color: #fff;
		padding: 24rpx 32rpx;
		display: flex;
		align-items: center;
		gap: 16rpx;
		border-bottom: 1rpx solid #f0f0f0;

		.service-avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
		}

		.service-name {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}
	}

	// 订单详情卡片
	.detail-cards {
		padding: 24rpx 32rpx;
	}

	.detail-card {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 16rpx;


    // 商品信息
    .order-product {
      display: flex;
      align-items: center;
      padding: 24rpx 32rpx;
      gap: 20rpx;

      .product-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 50%;
        flex-shrink: 0;
      }

      .product-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 8rpx;

        .product-title {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
          line-height: 1.4;
        }

        .product-desc {
          font-size: 24rpx;
          color: #666;
        }

        .order-time {
          font-size: 22rpx;
          color: #999;
          margin-top: 4rpx;
        }
      }

      .product-price {
        display: flex;
        align-items: baseline;
        gap: 4rpx;

        .price-symbol {
          font-size: 24rpx;
          color: #333;
        }

        .price-value {
          font-size: 32rpx;
          color: #333;
          font-weight: 600;
        }
      }
    }

		&.clickable {
			&:active {
				background-color: #f9f9f9;
			}
		}

		.detail-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 12rpx 0;

			.detail-label {
				font-size: 28rpx;
				color: #333;
			}

			.detail-value {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;

				&.address-value {
					max-width: 400rpx;
					word-break: break-all;
				}
			}

			.detail-value-with-arrow {
				display: flex;
				align-items: center;
				gap: 8rpx;

				.arrow-icon {
					width: 24rpx;
					height: 24rpx;
				}
			}

			.status-badge {
				padding: 8rpx 16rpx;
				border-radius: 8rpx;
				font-size: 24rpx;

				&.status-pending-pricing {
					background-color: #e3f2fd;
					color: #2196f3;
				}

				&.status-pending {
					background-color: #fff3e0;
					color: #539DF3;
				}

				&.status-paid {
					background-color: #e3f2fd;
					color: #2196f3;
				}

				&.status-shipped {
					background-color: #e8f5e8;
					color: #4caf50;
				}

				&.status-pending-receipt {
					background-color: #fff8e1;
					color: #ff9800;
				}

				&.status-completed {
					background-color: #e8f5e8;
					color: #4caf50;
				}

				&.status-cancelled {
					background-color: #f5f5f5;
					color: #999;
				}

				&.status-refunding {
					background-color: #ffebee;
					color: #f44336;
				}

				&.status-refunded {
					background-color: #f5f5f5;
					color: #999;
				}

				.status-text {
					font-weight: 500;
				}
			}

			&.price-row {
				.price-section {
					display: flex;
					align-items: baseline;
					gap: 4rpx;

					.price-symbol {
						font-size: 24rpx;
						color: #333;
					}

					.price-value {
						font-size: 32rpx;
						color: #539DF3;
						font-weight: 600;
					}
				}
			}
		}
	}

	// 备注
	.remarks-section {
		background-color: #fff;
		margin: 0 32rpx;
		border-radius: 12rpx;
		padding: 24rpx;

		.remarks-title {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
			margin-bottom: 16rpx;
			display: block;
		}

		.remarks-content {
			.remarks-text {
				font-size: 26rpx;
				color: #333;
				line-height: 1.6;
			}
		}
	}

	// 底部操作按钮
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 24rpx 32rpx;
		border-top: 1rpx solid #f0f0f0;

		.action-buttons {
			display: flex;
			gap: 16rpx;

			.action-btn {
				flex: 1;
				height: 88rpx;
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				font-weight: 500;

				&.reject-btn {
					background-color: #f5f5f5;
					color: #333;

					&:active {
						background-color: #e8e8e8;
					}
				}

				&.pay-btn {
					background-color: #333;
					color: #fff;

					&:active {
						background-color: #555;
					}
				}

				&.secondary-btn {
					background-color: #f5f5f5;
					color: #333;

					&:active {
						background-color: #e8e8e8;
					}
				}

				&.primary-btn {
					background-color: #539DF3;
					color: #fff;

					&:active {
						background-color: #e55a2b;
					}
				}

				.action-text {
					font-size: 28rpx;
				}
			}
		}
	}
</style>
